<?php
session_start();
?>
<html>
<head>
<?php
include ('head.php');
$HoTen = $_POST['tbx_hoten'];
$Email = $_POST['tbx_email'];
$DienThoai = $_POST['tbx_dienthoai'];
$DiaChi = $_POST['tbx_diachikh'];
$GhiChu = " ";

?>

</head>

<body>
		
<?php
include ('dbcon.php');
mysql_query("START TRANSACTION");
include ('webtitle.php');
include ('topbannermenu.php');
include ('leftmenu.php');
include ('rightmenu.php');

?>	
   
  <div id = "divMid">
      <div id = "pro4">
        <center>
       
<font color="#0000CC"> <br><h1>THANH TOÁN</h1></font>
<?php 
   
  
 
?>
<?php

$ok=1;
if(isset($_SESSION['DT']))
{
 foreach($_SESSION['DT'] as $k => $v)
 {
  if(isset($k))
  {
   $ok=2;
  }
 }
}
if($ok == 2)
{
   foreach($_SESSION['DT'] as $key=>$value)
   {
    $item[]=$key;
   }
   $str=implode(",",$item);
   $query=mysql_query("select * from sanpham where MaSP in ($str)");
   $total = 0;
   $dates = "";
   $sqldate = mysql_query("select now()");
   while($date = mysql_fetch_array($sqldate))
   {
	   $dates = $date[0];
 }
 $SL = 0;
 $SLTK = 0;
  $t = true;
   $id = "";
   $MaxDH = "";
   $sqlDH = mysql_query("insert into DonHang values ('null', '', '$dates', '$HoTen', '$DiaChi', '$Email', '$DienThoai','', 0,'$GhiChu')");
   $sqlMax = mysql_query("select max(madh) from donhang");
   
   while($rowdh = mysql_fetch_array($sqlMax))
   {
	   $MaxDH = $rowdh[0];
   }
	while($row=mysql_fetch_array($query))
   {
	   $SL = $_SESSION['DT'][$row[0]];
	   $SLTK = $row[6];
	   $id  = $row[0];
	   $DonGia = $_SESSION['DT'][$id];
	   $Gia = $_SESSION['DT'][$row[0]]*$row[3];
	   $t = mysql_query("insert into donhangchitiet values ('null', $MaxDH, $row[0],$DonGia,$Gia )");
	   if($t == false)
	   {
		   echo" thất bại";
		   mysql_query("ROLLBACK");
		}
		else
		mysql_query("COMMIT");
	   $total+=$_SESSION['DT'][$row[0]]*$row[3];
   }
   mysql_query("update donhang set tongtien = $total where madh = $MaxDH");
   if($t == true)
   {
   		echo "Thành Công ";
		 unset($_SESSION['DT']);
		 $xx = $SLTK - $SL;
		 mysql_query("update sanpham set soluongtonkho = $xx where masp = $id");
   }
   
}?>
  </div>

		<div class="clr"></div>
		<?php 
		include ('footer.php');
		?>
</body>
</html>

